package yxy.cherry.data.script;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.redisson.api.RBucket;

import yxy.apple.util.redisson.RedisConnection;

public class FomulaScript {
	static private FomulaScript instance;

	static public void init(RedisConnection connection) {
		if (instance == null) {
			instance = new FomulaScript();
			instance.connection = connection;
			instance.init();
		}
	}

	private RedisConnection connection;
	private ScriptEngine engine;

	private FomulaScript() {
	}

	private void init() {
		RBucket<String> bucket = connection.client().getBucket("DATA:" + "v1.0.0.0" + ":SCRIPT:" + "fomula");
		String script = bucket.get();
		try {
			ScriptEngineManager manager = new ScriptEngineManager();
			engine = manager.getEngineByName("javascript");
			engine.eval(script);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	synchronized static public Object gogog(String name, Object... params) throws NoSuchMethodException, ScriptException {
		Invocable invocable = (Invocable) instance.engine;// Invocable允许从java代码调用定义在脚本中的单个函数
		Object result = invocable.invokeFunction(name, params);// 调用脚本中定义的顶层程序和函数
		return result;
	}

	synchronized static public Double doubleValue(String name, Object... params) throws NoSuchMethodException, ScriptException {
		Invocable invocable = (Invocable) instance.engine;// Invocable允许从java代码调用定义在脚本中的单个函数
		Object result = invocable.invokeFunction(name, params);// 调用脚本中定义的顶层程序和函数
		if (result instanceof Double) {
			return (Double) result;
		}
		return Double.valueOf(0);
	}

	synchronized static public int intValue(String name, Object... params) throws NoSuchMethodException, ScriptException {
		Invocable invocable = (Invocable) instance.engine;// Invocable允许从java代码调用定义在脚本中的单个函数
		Object result = invocable.invokeFunction(name, params);// 调用脚本中定义的顶层程序和函数
		if (result instanceof Integer) {
			return (Integer) result;
		}
		return 0;
	}

	synchronized static public String stringValue(String name, Object... params) throws NoSuchMethodException, ScriptException {
		Invocable invocable = (Invocable) instance.engine;// Invocable允许从java代码调用定义在脚本中的单个函数
		Object result = invocable.invokeFunction(name, params);// 调用脚本中定义的顶层程序和函数
		if (result instanceof String) {
			return result.toString();
		}
		return null;
	}

}
